package se.opendataexchange.simulator;

import java.util.Date;
import java.util.HashMap;

import org.apache.log4j.Logger;

import se.opendataexchange.common.IAddressValueChanged;
import se.opendataexchange.common.InvalidAddressException;
import se.opendataexchange.controller.OpenDataExchangeController;

public class TestSimulator implements IAddressValueChanged {
	Logger log = Logger.getLogger(TestSimulator.class);
	public static void main(String[] args){
		new TestSimulator().runTest();
	}
	
	private HashMap<String, Long> times = new HashMap<String, Long>();
	private HashMap<String, Long> maxTimes = new HashMap<String, Long>();
	long tSample;
	
	private void runTest() {
		try {
			x();
		} catch (InvalidAddressException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
	}

	@Override
	public void valueHasChanged(String name, Object value, Date timestamp) {
		synchronized(this){
			if(times.get(name)!=null){
				long time = System.currentTimeMillis()-times.get(name);
				if(maxTimes.get(name) < time){
					maxTimes.put(name, time);
					System.out.println("New max "+time+" for "+name);
				}
				if (System.currentTimeMillis()-tSample > 3000){
					System.out.println("Time sample: "+name +": " +(System.currentTimeMillis()-times.get(name)));
					tSample = System.currentTimeMillis();
				}
				times.put(name, System.currentTimeMillis());
			}else{
				System.out.println("Not in map: "+name);
				times.put(name, System.currentTimeMillis());
				maxTimes.put(name, (long)0);
			}			
		}
	}
	
	
	private void x() throws InvalidAddressException{ 
		OpenDataExchangeController controller = OpenDataExchangeController.getController("controlsystems.xml");
		for(String val : controller.getAddressValues()){
			System.out.println("Subscribe to "+val);
			times.put(val, System.currentTimeMillis());
			maxTimes.put(val, (long)0);
			controller.subscribeForAddressValue(val, this);
		}
		tSample = System.currentTimeMillis();
	}
	
}
